import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class STab extends StatefulWidget {
  // tab 集合
  final List<String> tabs;

  // 页面集合
  final List<Widget> pages;

  STab({this.tabs, this.pages});

  @override
  _STabState createState() => _STabState();
}

class _STabState extends State<STab> {
  int selectedIndex = 0;
  SwiperController swipeControl = new SwiperController();

  // tab 索引变化回调
  void onTabChange(index) {
    setState(() {
      selectedIndex = index;
    });
    swipeControl.move(index);
  }

  void onCancelClick() {
    print('cancel');
  }

  void onPageChange(index) {
    setState(() {
      selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 15),
        child: Column(
      children: [
        TabLayout(widget.tabs, selectedIndex, onTabChange, onCancelClick),
        ContentLayout(widget.pages, swipeControl, onPageChange)
      ],
    ));
  }
}

/// 上面 Tab 的布局
Widget TabLayout(tabs, selectedIndex, onTabChange, onRightButtonClick) {
  List<Widget> getItem() {
    List<Widget> children = [];
    for (var i = 0; i < tabs.length; i++) {
      children.add(
        GestureDetector(
          onTap: () {
            onTabChange(i);
          },
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.only(left: 10),
                child: Text(tabs[i],
                    style: TextStyle(fontSize: selectedIndex == i ? 23 : 15)),
              ),
              selectedIndex == i?Container(
                height: 10,
                width: 10,
                padding: EdgeInsets.only(left: 10,bottom: 5),
                margin: EdgeInsets.only(bottom: 5),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                  color: Colors.amber,
                ),
              ):Container()
            ],
          ),
        ),
      );
    }
    return children;
  }

  return Row(
    mainAxisAlignment: MainAxisAlignment.start,
    children: getItem(),
  );
}

/// 下面页面内容布局
Widget ContentLayout(pages, swipeControl, onIndexChanged) {
  return Expanded(
    child: Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Swiper(
          itemCount: pages.length,
          itemBuilder: (BuildContext context, int index) {
            return pages[index];
          },
          loop: false,
          onIndexChanged: (index) {
            onIndexChanged(index);
          },
          controller: swipeControl,
        )),
  );
}
